$(function () {
    // 监听模态框事件
    $('#login').on('shown.bs.modal', function () {
        $('#lg-username').trigger('focus')
    })
    $('#register').on('shown.bs.modal', function () {
        $('#rg-username').trigger('focus')
    })
    doLogin = () => {
        let p = $('#login form').serializeArray();
        let params = {};
        $.each(p, function() {
            params[this.name] = this.value;
        });
        $.ajax({
            type: 'POST',
            url: '/user/login',
            data: JSON.stringify(params),
            headers: {
                'Content-Type': 'application/json'
            },
            success: res => {
                if (res.code === 0) {
                    toastr.success('登录成功')
                    location.reload()
                } else if (res.code === -1) {
                    toastr.error(res.message)
                }
            },
            dataType: 'json'
        })
    }
    doRegister = () => {
        let p = $('#register form').serializeArray();
        let params = {};
        $.each(p, function() {
            params[this.name] = this.value;
        });
        $.ajax({
            type: 'POST',
            url: '/user/register',
            data: JSON.stringify(params),
            headers: {
                'Content-Type': 'application/json'
            },
            success: res => {
                if (res.code === 0) {
                    toastr.success('注册成功')
                    location.reload()
                } else if (res.code === -1) {
                    toastr.error(res.message)
                }
            },
            dataType: 'json'
        })
    }
    doLogout = () => {
        $.ajax({
            type: 'POST',
            url: '/user/logout',
            success: res => {
                toastr.success('退出成功')
                location.reload()
            }
        })
    }
})